package com.timothy.repo;

import android.app.ListActivity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.Toast;
import com.markupartist.android.widget.PullToRefreshListView;
import com.sina.stock.data.SinaStockClient;
import com.sina.stock.data.SinaStockInfo;
import com.timothy.repo.adapter.RepoAdaptor;
import com.timothy.repo.bean.Repo;
import com.timothy.repo.data.ParseXML;
import com.timothy.repo.util.NetWorkUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Timothy on 13-6-23.
 */
public class RepoRefreshList extends ListActivity {
    public static final String LOG_TAG = "RepoRefreshList";

    Context mContext;
    RepoAdaptor adaptor ;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pull_to_refresh);

        mContext = getApplicationContext();
        

        // Set a listener to be invoked when the list should be refreshed.
        ((PullToRefreshListView) getListView()).setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // Do work to refresh the list here.
                new GetDataTask().execute();
            }
        });
        
        if(NetWorkUtil.isNetworkAvailable(mContext)){
        	mClient = SinaStockClient.getInstance();
        	new GetDataTask().execute();
        }else{
        	Toast.makeText(mContext, "Your network is not available!", Toast.LENGTH_LONG).show();
        }

        
    }

    private class GetDataTask extends AsyncTask<Void, Void, String[]> {

        @Override
        protected String[] doInBackground(Void... params) {
            // Simulates a background job.
            try {
                Thread.sleep(2000);
                loadData();
            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String[] result) {
            super.onPostExecute(result);

            adaptor = new RepoAdaptor(mContext, repoValueList);
            setListAdapter(adaptor);
            // Call onRefreshComplete when the list has been refreshed.
            ((PullToRefreshListView) getListView()).onRefreshComplete();

//            String content = reposNeedNotify(repoValueList);
//            if( content!=null && content.length()>0){
//                issueNotification(content);
//            }
        }
    }

    SinaStockClient mClient;
    List<String> codeList;
    List<Repo> repoList;
    List<Repo> repoValueList;

    public void loadData(){
        codeList = ParseXML.getRepoCodeList(mContext);
        Map<String,Double> codeValueMap = null; //code&info Map
        try {
            //获取证券代码和信息（key:代码 Value 信息）
            String[] array = new String[codeList.size()];
            codeList.toArray(array); // fill the array
            codeValueMap = mClient.getStockPrice(array);

            repoValueList = new ArrayList<Repo>();
            repoList = ParseXML.getRepoList(mContext);
            for (Repo repo : repoList) {
                String code= repo.getCode();
                repo.setPrice(codeValueMap.get(code));
                repoValueList.add(repo);
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, e.getMessage());
        } catch (SinaStockInfo.ParseStockInfoException e) {
            Log.e(LOG_TAG, e.getMessage());
        }
    }

    public String reposNeedNotify(List<Repo> repoValueList){
        StringBuffer sb = new StringBuffer();
        for (Repo repo : repoValueList) {
            if(repo.getPrice() >= 4){
                sb.append( (sb.length()>0) ? (","+repo.getName()): repo.getName());
            }
        }
        return sb.toString();
    }

/*    public void issueNotification(String content){
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle("My notification")
                        .setContentText(content);
        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(this, RepoRefreshList.class);

        // The stack builder object will contain an artificial back stack for the
        // started Activity.
        // This ensures that navigating backward from the Activity leads out of
        // your application to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(RepoRefreshList.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // mId allows you to update the notification later on.
        int mId=0;
        mNotificationManager.notify(mId, mBuilder.build());
    }*/

}